package com.ronghuanet.user.interceptor;

import com.ronghuanet.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1 从请求头中获取token
        String token = request.getHeader("token");
        //2 判断是否有token，
        // 2.1如果有，和redis比对OK，登录成功
        if (StringUtils.isNotBlank(token)){
            Logininfo logininfo = (Logininfo) redisTemplate
                    .opsForValue().get(token);
            if (logininfo!=null){//已经登录
                //@TODO 判断是否有权限 --->就是把权限系统权限判断逻辑拷贝到这儿就OK
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES); //模拟session30分钟过期，但是不间断访问
                return true;
            }

        }
        // 2.2 否则登录失败
        //都是登录是吧返回一个错误 {“success”:false,"message":"noLogin"}，让前端条页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
